package com.online_exam.controller.student;

import com.online_exam.base.RestResponse;
import com.online_exam.domain.User;
import com.online_exam.service.UserService;
import com.online_exam.viewmodel.student.user.InfoVM;
import com.online_exam.viewmodel.student.user.LoginVM;
import com.online_exam.viewmodel.student.user.RegisterVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@RestController("studentUserController")
@RequestMapping("/api/student/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public RestResponse register(@RequestBody RegisterVM registerVM) {
        String userName = registerVM.getUserName();
        String password = registerVM.getPassword();
        Integer level = registerVM.getUserLevel();
        if (userService.selectByUsername(userName) == null) {
            User user = new User();
            user.setUserUuid(UUID.randomUUID().toString());
            user.setUserName(userName);
            user.setPassword(password);
            userService.InsertUser(user);
            return RestResponse.ok();
        }
        return RestResponse.fail(2,"用户名已存在！" );
    }


    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public RestResponse update(@RequestBody InfoVM infoVM){
        User user = new User();
        user.setAge(infoVM.getAge());
        user.setBirthDay(infoVM.getBirthDay());
        user.setCreateTime(infoVM.getCreateTime());
        user.setImagePath(infoVM.getImagePath());
        user.setPhone(infoVM.getPhone());
        user.setRealName(infoVM.getRealName());
        user.setUserLevel(infoVM.getUserLevel());
        user.setUserName(infoVM.getUserName());
        user.setSex(infoVM.getSex());
        if (userService.update(user)==1){
            return RestResponse.ok();
        }
        return RestResponse.fail(2, "修改异常！");
    }

    @RequestMapping(value = "/current" ,method = RequestMethod.POST)
    public RestResponse current(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String studentUserName;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("studentUserName")){
                studentUserName=cookie.getValue();
                System.out.println("当前用户："+studentUserName);
                User user = userService.selectByUsername(studentUserName);
                System.out.println(user);
                return RestResponse.ok(user);
            }
        }
        return RestResponse.fail(2, "获取当前用户异常！");
    }

}
